package com.gqz.aircraftwar.mvp.model.buff

import android.graphics.Canvas
import android.graphics.PointF
import com.gqz.aircraftwar.App
import com.gqz.aircraftwar.mvp.model.aircraft.PlayerAircraft
import com.gqz.aircraftwar.util.MyEnum
import com.gqz.aircraftwar.util.i
import kotlinx.coroutines.*
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.random.Random

/**
 * Descraption
 *
 * @author gqz
 * @data 2020/4/11
 */
class BuffManager {
    private val TAG: String = "BuffManager-->"

    val ctx = newSingleThreadContext("Buff")
    var job: Job? = null
    var buffList = CopyOnWriteArrayList<Buff>()

    companion object {
        val instance = BuffManager()
        private const val interval = 1000L / 30L
    }

    fun start() {
        try {
            job = GlobalScope.launch(ctx) {
                while (App.isRunning) {
                    buffList.filter { !it.added }.forEach {
                        it.move()
                        it.hit(PlayerAircraft.getInstant())
                    }
                    delay(interval)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun stop() {
        buffList.clear()
        job?.cancel()
    }

    fun generateBuff(pos: PointF) {
        var type = MyEnum.BuffType.values()[Random.nextInt(MyEnum.BuffType.values().size - 2) + 1]
        lateinit var buff: Buff
        when (type) {
            MyEnum.BuffType.Scattering -> {
                buff = ScatteringBuff()
                i(TAG, "generateBuff--> ScatteringBuff")
            }
            MyEnum.BuffType.AtkSpeed -> {
                buff = AtkSpeedBuff()
                i(TAG, "generateBuff--> AtkSpeedBuff")
            }
            else -> {
                buff = Buff.Null
            }
        }
        if (buff !is NullBuff) {
            buff.pos = pos
            buffList.add(buff)
        }
    }

    fun drawAll(canvas: Canvas) {
        buffList.filter { !it.added }.forEach { it.draw(canvas) }
    }

}